package mvc.controller;

import mvc.config.MyBatisConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Controller
public class  CheckLogin{
    @RequestMapping(value = "/checklogin.do", produces = "text/html;charset=utf-8")
    @ResponseBody
    public ModelAndView checkLogin(String username, String password, ModelMap map) {
        System.out.println("checklogin开始");
        System.out.println(username);
        if (username==""||password==""){
            map.put("a","账号或密码错误");
            return new ModelAndView("login");
        }else {
            AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyBatisConfig.class);
            DataSource dataSource = ctx.getBean("dataSource",DataSource.class);
            try (Connection conn = dataSource.getConnection()) {
                String sql = "select password from user where username=?";
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1, username);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    String pwd = rs.getString(1);
                    if(pwd.equals(password)){
                        System.out.println("登陆成功");
                    }else {
                        map.put("a","账号或密码错误");
                        System.out.println("账号或密码错误");
                        return new ModelAndView("login");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ModelAndView("success");
        }
    }
}
